﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DACU.Properties;
using DACU.Tools;
using DACU.Tools.WebBrowser;
using DACU.UserControls;
using DACU.VkontakteApi.Base;
using DACU.VkontakteApi.Collections;
using DACU.VkontakteApi.Enums;

namespace DACU.VkontakteApi
{
	class VKApi
	{
		public const string AppId = "2154279";
		public static readonly VKResponseFormats VKResponseFormat = VKResponseFormats.XML;
		public const string VKApiVersion = "3.0";
		private static string _loginResponseFragment;
		static readonly BrowserTools Bt = new BrowserTools();

		private static SessionInfo _session;
		public static SessionInfo Session
		{
			get { return _session; }
		}

		private static bool _isLogged;
		public static bool IsLogged
		{
			get { return _isLogged; }
		}

		private static string _currentUserId;
		public static string CurrentUserId
		{
			get { return _currentUserId; }
		}

		public static bool Login()
		{
			Bt.Navigated += BtNavigated;
			const VKPermissions perms = VKPermissions.Audio | VKPermissions.Friends | VKPermissions.ExtendedMessages;
			Bt.Show(URLTemplates.GetLoginUrl(AppId,perms));
			if(String.IsNullOrWhiteSpace(_loginResponseFragment)) return false;
			var response = Utils.JsonToData(Utils.UrlDecode(_loginResponseFragment)) as Dictionary<string, object>;
			if (response != null)
				_session = new SessionInfo
				          	{
				          		_permissions = (int) perms,
				          		Expire = response.TryGetInt("expire"),
				          		Secret = response.TryGetString("secret"),
				          		Id = response.TryGetString("sid"),
				          		Signature = response.TryGetString("sig"),
				          		UserId = _currentUserId = response.TryGetString("mid")
				          	};
			return _isLogged = _session != null;
		}

		static void BtNavigated(object sender, System.Windows.Forms.WebBrowserNavigatedEventArgs e)
		{
			if (e.Url.LocalPath.EndsWith(Resources.SuccessLoginUrlEnd))
			{
				Bt.Close();
				_loginResponseFragment = e.Url.Fragment.Replace("#session=", "");
			}
		}

		public static VKFriendsCollection GetFriends(int? uid = null, VKFields fields = VKFields.All, VKNameCaseEnum vkNameCase = VKNameCaseEnum.None, int count = 0, int offset = 0, int? lid = null)
		{
			if (!IsLogged)
			{
				Login();
				return GetFriends(uid, fields, vkNameCase, count, offset, lid);
			}
			var parametrs = new VKParametrCollection();
			if(uid!=null)
				parametrs.Add("uid", uid.ToString());
			if (vkNameCase != VKNameCaseEnum.None)
				parametrs.Add("name_case", vkNameCase.ToString());
			if(count>0)
				parametrs.Add("count", count.ToString());
			if(offset>0)
				parametrs.Add("offset", offset.ToString());
			if (lid != null)
				parametrs.Add("lid", lid.ToString());
			var response = VKRequest.MethodResponse(VKMethods.GetFriends, null, fields);
			return VKFriendsCollection.ParseResponse(response,VKResponseFormat);
		}

		public static VKAudioCollection GetAudioCollection(int? uid=null,int? gid=null,VKIdsCollectionHelper<int> aids=null,bool need_user = false)
		{
			if (!IsLogged)
			{
				Login();
				return GetAudioCollection(uid, gid, aids, need_user);
			}
			var parametrs = new VKParametrCollection();
			if (aids != null && uid==null && gid==null)
				parametrs.Add("uid",CurrentUserId);
			if(aids != null)
				parametrs.Add("aids", aids.ToFormatedString());
			if (gid != null)
				parametrs.Add("gid", gid.ToString());
			else
				if (uid != null)
					parametrs.Add("uid", uid.ToString());
			if (need_user) parametrs.Add("need_user", "1");
			string response = VKRequest.MethodResponse(VKMethods.GetAudios, parametrs);
			return VKAudioCollection.ParseResponse(response, VKResponseFormat);
		}

		public static VKUserProfile GetProfiles(VKIdsCollectionHelper<int> uids=null,VKDomainCollection vkDomains=null,VKFields fields=VKFields.uid,VKNameCaseEnum vkNameCase= VKNameCaseEnum.None)
		{
			if (!IsLogged)
			{
				Login();
				return GetProfiles(uids, vkDomains, fields, vkNameCase);
			}
			var parametrs = new VKParametrCollection();
			if (vkDomains != null)
				parametrs.Add("domains", vkDomains.ToFormatedString());
			else
				parametrs.Add("uids", uids != null?uids.ToFormatedString():CurrentUserId);
			if(vkNameCase!= VKNameCaseEnum.None)
				parametrs.Add("name_case", vkNameCase.ToString());
			string response = VKRequest.MethodResponse(VKMethods.GetProfiles, parametrs, fields);
			return VKUserProfile.ParseResponse(response,VKResponseFormat);
		}
	}
}
